package com.atguigu.serviceorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.serviceorder.entity.TOrder;
import com.atguigu.serviceorder.service.TOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author JY
 * @since 2021-02-03
 */
@RestController
//@CrossOrigin
@RequestMapping("/serviceorder/order")
public class TOrderController {

    @Autowired
    private TOrderService orderService;

    //根据课程id和请求头传过来的token生成订单
    @PostMapping("createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request){
        //返回订单号
        String orderNo = orderService.createOrder(courseId, JwtUtils.getMemberIdByJwtToken(request));
        return R.ok().data("orderId", orderNo);
    }

    //根据id获取订单信息
    @GetMapping("getOrder/{orderId}")
    public R get(@PathVariable String orderId) {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        TOrder order = orderService.getOne(wrapper);
        return R.ok().data("item", order);
    }

    //根据用户id和课程id查询订单是否已被购买
    @GetMapping("isBuyCourse/{memberId}/{courseId}")
    public boolean isBuyCourse(@PathVariable String memberId,@PathVariable String courseId){
        int count = orderService.count(new QueryWrapper<TOrder>().
                eq("member_id", memberId).eq("course_id", courseId).eq("status", 1));
        return count>0?true:false;
    }
}

